package nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

public class GroupChatClient2 {
    private static final String HOST = "127.0.0.1";
    private static final int PORT = 6667;
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;

    public GroupChatClient2() throws IOException {
        selector = Selector.open();
        /**
         * 连接服务器
         */
        socketChannel = socketChannel.open(new InetSocketAddress(HOST,PORT));
        /**
         * 设置非阻塞
         */
        socketChannel.configureBlocking(false);
        /**
         * 将channel注册到selector
         */
        socketChannel.register(selector, SelectionKey.OP_READ);
        /**
         * 得到username
         */
        username = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println(username +"is OK");
    }

    /**
     * 发送消息到服务器
     * @param info
     */
    public void sendInfo(String info){
        info = username + "说： "+info;
        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    /**
     * 读取服务器端传来的消息
     */
    public void readInfo(){
        try {
            int readChannels = selector.select();
            /**
             * 有事件发生
             */
            if (readChannels > 0){
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    if (key.isReadable()){
                        /**
                         * 得到相关的通道
                         */
                        SocketChannel channel = (SocketChannel) key.channel();
                        /**
                         * 得到缓冲区
                         */
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        /**
                         * 读取
                         */
                        channel.read(byteBuffer);
                        /**
                         * 转为字符串
                         */
                        String s = new String(byteBuffer.array());
                        System.out.println(s.trim());

                    }
                }
                iterator.remove();
            }
            else {
                // System.out.println("没有可用的通道");
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        /**
         * 启动客户端
         */
        GroupChatClient chatClient = new GroupChatClient();

        /**
         * 每隔三秒读一次消息
         */
        new Thread(){
            public void run(){
                while (true){
                    /**
                     * 读取消息
                     */
                    chatClient.readInfo();
                    try {
                        Thread.currentThread().sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        /**
         * 发送消息
         */
        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNextLine()){
            String s = scanner.nextLine();
            chatClient.sendInfo(s);
        }
    }
}
